﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Collections;
using System.DirectoryServices;

namespace Aplicacion.lib
{
    public class Zimbra
    {
        private DirectoryEntry _de;

        public Zimbra(string LDAPPath, string user, string pass)
        {
            _de = new DirectoryEntry(LDAPPath, user, pass, AuthenticationTypes.None);
        }



        public IEnumerable<SearchResult> getUsers()
        {
            using (var deSearch = new DirectorySearcher(_de))
            {
                deSearch.Filter = "(&(objectClass=zimbraAccount))";
                deSearch.SearchScope = SearchScope.Subtree;

                SearchResultCollection results = deSearch.FindAll();
                if (results.Count > 0)
                {
                    foreach (SearchResult item in results)
                    {
                        yield return item;
                    }
                }

            }
        }


        /*

        public static SortedList getLDAPUsers(string LDAPPath, string user, string pass)
        {
            SortedList ldapList = new SortedList();

            //String myADSPath = @"LDAP://10.1.11.191:389/ou=people,dc=tierradelfuego,dc=gov,dc=ar";

            string myADSPath = LDAPPath;
            // Create an Instance of DirectoryEntry.
            DirectoryEntry myDirectoryEntry = 

            // Get the Child ADS objects.
            ///Console.WriteLine("The Child ADS objects are:");

            string uid = string.Empty;
            foreach (DirectoryEntry myChildDirectoryEntry in myDirectoryEntry.Children)
            {
                uid = getUID(myChildDirectoryEntry.Path);
                ldapList.Add(uid, uid);
            }

            //Console.WriteLine(getUID(myChildDirectoryEntry.Path));
            //Console.ReadLine();
            return ldapList;

        }
        private static string getUID(string value)
        {
            string aux = string.Empty;
            int index = value.IndexOf("uid");
            if (index == -1)
                return string.Empty;

            for (int i = index + 4; i < value.Length; i++)
            {
                if (value[i] != ',')
                    aux += value[i];
                else break;
            }
            return aux;
        }
         * 
         * */
    }
}